package com.example.ext.jwt;

import com.example.entity.authority.SystemUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;

/**
 * Created by youkun on 2017/8/13.
 */
public class TokenUtils {
    public static final String AUTH_HEADER = "Authorization";
    public static final String SECRET_KEY = "secretkey";

    private TokenUtils(){}

    public static Claims parseToken(final String authHeader) throws Exception{
        final String token = authHeader.substring(7); // The part after "Bearer ";

        final Claims claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody();

        return claims;
    }

    public static String generateToken(final SystemUser login){
        Date now = new Date();
        String token = Jwts.builder()
                .setSubject(login.getUserName())
                .claim("role", "USER")
                .setIssuedAt(now)
                .setExpiration(DateUtils.addMinutes(now, 60))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
        return token;
    }
}
